/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl;
import contractmessageservice.ContractMessage;
import dao.DerbyDao;
import electricitysupplier.T1ES1;
import es2service.TestService;
import es2service.TestServiceSoap;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.datatype.XMLGregorianCalendar;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import service.ContractService;

/** 
 *
 * @author Yuuzaa
 */
public class ContractController extends SimpleFormController {

    private ContractService contractService;
    private T1ES1 t1Service;
    private TestServiceSoap es2Service;

    public ContractController() {
        //Initialize controller properties here or 
        //in the Web Application Context
        t1Service = new T1ES1();
        setCommandClass(Contract.class);
        setCommandName("name");
        setSuccessView("contractView");
        setFormView("nameView");
    }

//Use onSubmit instead of doSubmitAction 
//when you need access to the Request, Response, or BindException objects
    @Override
    protected ModelAndView onSubmit(
            HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors) throws Exception {
        Contract contract = (Contract) command;
        Date startDate = null;
        Date endDate = null;
        String area = null;
        String facility = null;
        String actionId = request.getParameter("actionId");
        System.out.print("" + contract.getStartDate());
        DerbyDao dao = new DerbyDao();
        List<ContractMessage> cms = new ArrayList<ContractMessage>();
        cms = dao.getMessages();
        DateFormat formatter;
        formatter = new SimpleDateFormat("dd.MM.yyyy");
        if ("Get messages".equals(actionId)) {
            ModelAndView mav = super.onSubmit(request, response, command, errors);
            mav.addObject("messageList", cms);
            return mav;
        }
        if ("Send message to supplier".equals(actionId)) {
            es2Service = new TestService().getTestServiceSoap();
            ContractMessage templateMsg = new ContractMessage();
            for (ContractMessage ccm : cms) {
                if (request.getParameter("messageId") != null && request.getParameter("messageId").equals(ccm.getMessageId())) {
                    templateMsg = ccm;
                }
            }
            electricitysupplier.ContractMessage ecm = ContractMessageConverter.convertContract(templateMsg);
            if (contract.getStartDate() != null && !contract.getStartDate().isEmpty()) {
                startDate = (Date) formatter.parse(request.getParameter("startDate"));
                GregorianCalendar cal = new GregorianCalendar();
                cal.setTime(startDate);
                XMLGregorianCalendar xmlCal = new XMLGregorianCalendarImpl(cal);
                ecm.getContractInfo().setStartDate(xmlCal);
            } else {
                startDate = ecm.getContractInfo().getStartDate().toGregorianCalendar().getTime();
            }
            if (contract.getEndDate() != null && !contract.getEndDate().isEmpty()) {
                endDate = (Date) formatter.parse(request.getParameter("endDate"));
                GregorianCalendar cal = new GregorianCalendar();
                cal.setTime(endDate);
                XMLGregorianCalendar xmlCal = new XMLGregorianCalendarImpl(cal);
                ecm.getContractInfo().setEndDate(xmlCal);
            } else {
                if (ecm.getContractInfo().getEndDate() != null) {
                    endDate = ecm.getContractInfo().getEndDate().toGregorianCalendar().getTime();
                }
            }
            if (contract.getArea() != null) {
                area = request.getParameter("areaId");
                ecm.getClientParty().setAreaId(area);
            } else {
                area = ecm.getClientParty().getAreaId();
            }
            if (contract.getFacility() != null) {
                facility = request.getParameter("facilityId");
                ecm.getClientParty().setFacilityId(facility);
            } else {
                facility = ecm.getClientParty().getFacilityId();
            }
            if ("T1ES1".equals(templateMsg.getProviderParty().getName())) {//if the new contract is from ES1
                ecm.setConfirmed("on".equals(request.getParameter("isConfirmation")));
                dao.createContract(Integer.parseInt(request.getParameter("supplierId")), Integer.parseInt(request.getParameter("clientId")), startDate, endDate, area, facility, request.getParameter("settlementMethod"));
                t1Service.getBasicHttpBindingIT1ES1Service().receiveSupplierChangeConfirmation(ecm);
                System.out.print("ES1 ! ");
                if (ecm.isConfirmed()) {
                    System.out.print("ES2 ! confirmed ");
                    es2Service.clientLeaving(ecm.getProviderParty().getRegistryCode());
                }
            } else if ("T1ES2".equals(templateMsg.getProviderParty().getName())) {//if the new contract is from ES2
                if("on".equals(request.getParameter("isConfirmation"))){
                    es2Service.clientApproved(ecm.getProviderParty().getRegistryCode());
                    dao.createContract(Integer.parseInt(request.getParameter("supplierId")), Integer.parseInt(request.getParameter("clientId")), startDate, endDate, area, facility, request.getParameter("settlementMethod"));
                    ecm.setConfirmed("on".equals(request.getParameter("isConfirmation")));
                    t1Service.getBasicHttpBindingIT1ES1Service().receiveCustomerChangedSupplier(ecm);
                }
                else{
                    ModelAndView mvnm = new ModelAndView("messageSent");
                    mvnm.addObject("messageSent", contractService.sayResult("No message to send."));
                    return mvnm;
                }
            }

            ModelAndView mv = new ModelAndView("messageSent");
            mv.addObject("messageSent", contractService.sayResult("Message sent."));
            return mv;
        }
        return null;
    }

    public void setContractService(ContractService contractService) {
        this.contractService = contractService;
    }
}
